const { blog_article, blog_tag, dictionary_type, dictionary_items, blog_user, article_types } = require('@/model');
const { Sequelize } = require('sequelize');

class ArticleService {
  async deleteArticle(id) {
    return await blog_article.destroy({
      where: {
        id,
      },
    });
  }

  // 保存文章 id存在是修改 id不存在是新增
  // upsert性能略低于分开操作  可以手动判断id 是否存在来选择是更新还是新增
  // 或者分开接口 
  async saveArticle(params) { 
    const { tagList = [], category_id, ...rest } = params;
    const article_type = await article_types.findOne({
      where: {
        id: category_id
      }
    });
    if (!article_type) {
      throw new Error(`未找到分类 ${category_id}`);
    }


    // const category = await dictionary_type.findOne({
    //   where: { id: params.category_id },
    //   include: [{
    //     model: dictionary_items,
    //     where: {
    //       value: params.category_id
    //     },
    //     as: 'itemsById'
    //   }]
    // });
    // if (!category) {
    //   throw new Error(`未找到分类 ${params.category_id}`);
    // }
    const tagPromises = tagList.map(async (tagName) => {
      const [tagInstance] = await blog_tag.findOrCreate({ where: { name: tagName } }); // 查找或创建标签
      return tagInstance;
    });
    const tagInstances = await Promise.all(tagPromises);
    // params 里包含 id 时为更新，不包含 id 时为新增
    const [article, created] = await blog_article.upsert(rest);
    // article 是数据实例，created 为 true 表示新建，false 表示更新
    await article.setTags(tagInstances);
    console.log('article:', article);
    return article;
  }

  async getArticleList({ pageSize = 10, pageIndex = 1 }) {
    const conditions = {
      include: [ // 关联查询
        {
          model: blog_tag,
          as: 'tags',
          through: { attributes: [] }, // 不返回中间表字段
          attributes: ['id', 'name'],
        }, {
          model: dictionary_items,
          as: 'article_category',
          // attributes: [],
        }, {
          model: blog_user,
          as: 'article_author',
          // attributes: [],
        }
      ],
      attributes: {
        exclude: ['content'], // 排除内容字段
        // include:[
        //   [Sequelize.col('article_category.label'), 'category_name'],
        //   [Sequelize.col('article_author.username'), 'author_name'], // 使用 Sequelize.literal 获取作者名称
        //   [Sequelize.col('article_author.nickname'), 'author_nickname'], // 使用 Sequelize.literal 获取
        // ]
      },
      distinct: true, // 去重
      order: [['updatedAt', 'DESC']], // 按更新时间降序排列
    };

    if (pageSize < 1) {
      const res = await blog_article.findAll({
        ...conditions
      });
      return {
        total: res.length,
        list: res
      };
    }
    const offset = (pageIndex - 1) * pageSize;
    const res = await blog_article.findAndCountAll({ // 分页查询
      offset,
      limit: pageSize,
      ...conditions
    });

    const { count, rows } = res;
    return {
      total: count,
      list: rows
    };
  }

  async getArticleDetail(id) {
    const article = await blog_article.findOne({
      where: {
        id,
      },
      attributes: {
        include: [
          [Sequelize.col('article_category.label'), 'category_name'] // 使用 Sequelize.literal 获取分类名称
        ]
      },
      include: [
        {
          model: blog_tag,
          as: 'tags',
          through: { attributes: [] }, // 不返回中间表字段
          attributes: ['id', 'name'],
        },
        {
          model: dictionary_items,
          as: 'article_category',
          attributes: [],
        },
        {
          model: blog_user,
          as: 'article_author',
          attributes: ['id', 'username', 'nickname', 'avatar'], // 只返回需要的字段
        }
      ],
    });
    return article
  }

}

module.exports = new ArticleService();